package com.xrtn.utils;


import com.xrtn.bean.SysAccountCardInfo;
import org.apache.commons.lang.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by tu_pei on 2017/7/25.
 */
public class DateUtils {
    public static String YYYY_MM_DD = "yyyy-MM-dd";
    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    public static String HH_MM_SS = "HH:mm:ss";
    public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    /**
     * 获得默认的 date pattern
     */
    public static String getDatePattern()
    {
        return YYYY_MM_DD_HH_MM_SS;
    }

    /**
     * 返回预设Format的当前日期字符串
     */
    public static String getToday(){
        Date today = new Date();
        return format(today);
    }

    /**
     * 使用预设Format格式化Date成字符串
     */
    public static String format(Date date)
    {
        return date == null ? " " : format(date, getDatePattern());
    }

    /**
     * 使用参数Format格式化Date成字符串
     */
    public static String format(Date date, String pattern){
        return date == null ? " " : new SimpleDateFormat(pattern).format(date);
    }
    /**
     * 使用预设格式将字符串转为Date
     */
    public static Date parse(String strDate) throws ParseException{
        return StringUtils.isBlank(strDate) ? null : parse(strDate,
                getDatePattern());
    }

    /**
     * 使用参数Format将字符串转为Date
     */
    public static Date parse(String strDate, String pattern)
            throws ParseException{
        return StringUtils.isBlank(strDate) ? null : new SimpleDateFormat(
                pattern).parse(strDate);
    }

    /**
     * 在日期上增加数个整月
     */
    public static String addMonth(Date date, int n){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, n);
        return format(cal.getTime(),YYYY_MM_DD);
    }
    /**
     * 获取当天最后一秒
     * @param date
     * @return
     */
    public static Date getDayLastSecond(Date date){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 999);
        return cal.getTime();
    }
    /**
     * 日期增加
     * @param date
     * @param n
     * @return
     */
    public static String addDay(Date date, int n){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_MONTH,cal.get(Calendar.DAY_OF_MONTH)+n);//让日期加1
        return format(cal.getTime(),YYYY_MM_DD);
    }

    public static String getLastDayOfMonth(String year, String month){
        Calendar cal = Calendar.getInstance();
        // 年
        cal.set(Calendar.YEAR, Integer.parseInt(year));
        // 月，因为Calendar里的月是从0开始，所以要-1
        // cal.set(Calendar.MONTH, Integer.parseInt(month) - 1);
        // 日，设为一号
        cal.set(Calendar.DATE, 1);
        // 月份加一，得到下个月的一号
        cal.add(Calendar.MONTH, 1);
        // 下一个月减一为本月最后一天
        cal.add(Calendar.DATE, -1);
        return String.valueOf(cal.get(Calendar.DAY_OF_MONTH));// 获得月末是几号
    }
    //由出生日期获得年龄
    public static int getAge(Date birthDay) throws Exception {
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthDay)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;
            }else{
                age--;
            }
        }
        return age;
    }
    public static Date getDate(String year, String month, String day)
            throws ParseException{
        String result = year + "-"
                + (month.length() == 1 ? ("0 " + month) : month) + "-"
                + (day.length() == 1 ? ("0 " + day) : day);
        return parse(result);
    }

    /**
     * 获取当前时间
     * @return
     */
    public static Date getStartTime() {
        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        return todayStart.getTime();
    }

    /**
     * 获取当前最后一秒
     * @return
     */
    public static Date getEndTime() {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTime();
    }

    /**
     * 获取本周最后一天
     * @param day
     * @return
     */
    public static String getWeekLastDay(String day){
        Calendar cal = Calendar.getInstance();

        try {
            cal.setTime(new SimpleDateFormat(YYYY_MM_DD).parse(day));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        int d = 0;
        if(cal.get(Calendar.DAY_OF_WEEK)==1){
            d = -6;
        }else{
            d = 2-cal.get(Calendar.DAY_OF_WEEK);
        }
        cal.add(Calendar.DAY_OF_WEEK, d);
        cal.add(Calendar.DAY_OF_WEEK, 6);
        return new SimpleDateFormat(YYYY_MM_DD).format(cal.getTime());
    }
    /**
     * 获取本周第一天
     * @param day
     * @return
     */
    public static String getWeekFristDay(String day) {
        Calendar cal = Calendar.getInstance();

        try {
            cal.setTime(new SimpleDateFormat(YYYY_MM_DD).parse(day));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        int d = 0;
        if(cal.get(Calendar.DAY_OF_WEEK)==1){
            d = -6;
        }else{
            d = 2-cal.get(Calendar.DAY_OF_WEEK);
        }
        cal.add(Calendar.DAY_OF_WEEK, d);
        return new SimpleDateFormat(YYYY_MM_DD).format(cal.getTime());
    }

    /**
     * 获取本月最后一天
     * @return
     */
    public static String getMonthsLastDay(String day) {
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(new SimpleDateFormat(YYYY_MM_DD).parse(day));
        }catch (Exception ex){
            ex.printStackTrace();
        }
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        Date firstDayOfMonth = calendar.getTime();
        calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        return format(calendar.getTime(),YYYY_MM_DD);
    }
    /**
     * 获取本月第一天
     * @return
     */
    public static String getMonthsFristDay(String day) {
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(new SimpleDateFormat(YYYY_MM_DD).parse(day));
        }catch (Exception ex){
            ex.printStackTrace();
        }
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        Date firstDayOfMonth = calendar.getTime();
        calendar.add(Calendar.MONTH, 0);
        return format(calendar.getTime(),YYYY_MM_DD);
    }
    /**
     * 取得当月天数
     * */
    public static int getCurrentMonthLastDay(String day)
    {
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(new SimpleDateFormat(YYYY_MM_DD).parse(day));
        }catch (Exception ex){
            ex.printStackTrace();
        }
        calendar.set(Calendar.DATE, 1);//把日期设置为当月第一天
        calendar.roll(Calendar.DATE, -1);//日期回滚一天，也就是最后一天
        int maxDate = calendar.get(Calendar.DATE);
        return maxDate;
    }

    /**
     * 获取两个时间间隔多少天
     * @param startDate
     * @param endDate
     * @return
     */
    public static int getDateDifference(Date startDate,Date endDate){
        long l = endDate.getTime()-startDate.getTime();

        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");//如2016-08-10 20:40
        String fromDate = simpleFormat.format(startDate);
        String toDate = simpleFormat.format(endDate);
        try{
            long from = simpleFormat.parse(fromDate).getTime();
            long to = simpleFormat.parse(toDate).getTime();
            return (int) ((to - from)/(1000 * 60 * 60 * 24)) + 1;
        }catch (Exception e){
        }
        return 0;
    }
    /**
     * 获取两个时间间隔多少天
     * @param startDate
     * @param endDate
     * @return
     */
    public static int getHourDifference(Date startDate,Date endDate){
        long l = endDate.getTime()-startDate.getTime();
        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");//如2016-08-10 20:40
        String fromDate = simpleFormat.format(startDate);
        String toDate = simpleFormat.format(endDate);
        try{
            long from = simpleFormat.parse(fromDate).getTime();
            long to = simpleFormat.parse(toDate).getTime();
            return (int) ((to - from)/(1000 * 60 * 60)) + 1;
        }catch (Exception e){
        }
        return 0;
    }
    public static int getDayDifference(Date startDate,Date endDate){
        long l = endDate.getTime()-startDate.getTime();
        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");//如2016-08-10 20:40
        String fromDate = simpleFormat.format(startDate);
        String toDate = simpleFormat.format(endDate);
        try{
            long from = simpleFormat.parse(fromDate).getTime();
            long to = simpleFormat.parse(toDate).getTime();
            return (int) ((to - from)/(1000 * 60 * 60 * 24)) + 1;
        }catch (Exception e){
        }
        return 0;
    }
    public static Date getMonthStart(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int index = calendar.get(Calendar.DAY_OF_MONTH);
        calendar.add(Calendar.DATE, (1 - index));
        return calendar.getTime();
    }
    /**
     * start
     * 本周开始时间戳 - 以星期一为本周的第一天
     */
    public static Date getWeekStartTime(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        date = cal.getTime();
        return date;
    }

    public static Date getMonthEnd(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 1);
        int index = calendar.get(Calendar.DAY_OF_MONTH);
        calendar.add(Calendar.DATE, (-index));
        return calendar.getTime();
    }

    public static Date getNext(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, 1);
        return calendar.getTime();
    }
    //判断选择的日期是否是本月
    public static boolean isThisMonth(long time)
    {
        return isThisTime(time,"yyyy-MM");
    }
    private static boolean isThisTime(long time,String pattern) {
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String param = sdf.format(date);//参数时间
        String now = sdf.format(new Date());//当前时间
        if(param.equals(now)){
            return true;
        }
        return false;
    }
    public static List<String> getMonthDateList(Date d){
        Date date = DateUtils.getMonthStart(d);
        Date monthEnd = DateUtils.getMonthEnd(d);
        if(isThisMonth(d.getTime())){
            monthEnd = new Date();
        }else{
            monthEnd = DateUtils.getMonthEnd(d);
        }
        List<String> dateList = new ArrayList<>();
        while (!date.after(monthEnd)) {
            dateList.add(sdf.format(date));
            date = DateUtils.getNext(date);
        }
        return dateList;
    }
    public static List<String> getMonthDateList(String s) {
        List<String> dateList = new ArrayList<>();
        try{
            Date date = DateUtils.parse(DateUtils.getWeekFristDay(s),DateUtils.YYYY_MM_DD);
            Date monthEnd = DateUtils.parse(DateUtils.getWeekLastDay(s),DateUtils.YYYY_MM_DD);
            while (!date.after(monthEnd)) {
                dateList.add(sdf.format(date));
                date = DateUtils.getNext(date);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return dateList;
    }

    public static boolean isAmOrPm(Date date){
        GregorianCalendar ca = new GregorianCalendar();
        ca.setTime(date);
        return ca.get(GregorianCalendar.AM_PM)>0?true:false;
    }

    /**
     * 获取当前日期是星期几<br>
     *
     * @param dt
     * @return 当前日期是星期几
     */
    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);

        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;

        return weekDays[w];
    }

    /**
     * 获取当前日期是星期几<br>
     *
     * @param day 1,2,3,4,5,6,7
     * @return 当前日期是星期几
     */
    public static String getWeekOfIntegerDay(Integer day) {
        String[] weekDays = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
        if (day < 1) day = 1;
        if (day > 7) day = 7;

        return weekDays[day - 1];
    }


    /**
     * 时间差得到 年-月-日
     * @param curr
     * @param join
     * @return
     */
    public static String getDate(Calendar curr, Calendar join){

        int day = curr.get(Calendar.DAY_OF_MONTH) - join.get(Calendar.DAY_OF_MONTH);

        int month = curr.get(Calendar.MONTH) - join.get(Calendar.MONTH);

        int year = curr.get(Calendar.YEAR) - join.get(Calendar.YEAR);

        if (day < 0) {

            month -= 1;

            curr.add(Calendar.MONTH, -1);

            day = day + curr.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
        if (month < 0) {

            month = (month + 12) % 12;

            year--;
        }
        System.out.println("年龄：" + year + "年" + month + "月" + day + "天");

        String dateStr = year+"岁"+month+"月"+day+"天";

        return dateStr;
    }

    public static void main(String[] args) throws Exception {

//        // 当前日期
//        String str = DateUtils.format(new Date(),DateUtils.YYYY_MM_DD);
//        Date date = DateUtils.parse(str,DateUtils.YYYY_MM_DD);
//        Calendar dq = Calendar.getInstance();
//        dq.setTime(date);
//
//         //默认初始值日期
//        String dd = "2015-2-12";
//        Date date2 = DateUtils.parse(dd,DateUtils.YYYY_MM_DD);
//        Calendar rz = Calendar.getInstance();
//        rz.setTime(date2);
//
//        System.out.println(getDate(dq,rz));

//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//
//        Date date = format.parse("2013-02-01 00:00:00");
//        //开始时间
//        Calendar start = Calendar.getInstance();
//        start.setTime(date);
//        //结束时间
//        Calendar end = Calendar.getInstance();
//
//        if (!start.after(end)){
//            int subMonthCount =
//                    (end.get(Calendar.YEAR) - start.get(Calendar.YEAR) == 0)
//                            ? end.get(Calendar.MONTH) - start.get(Calendar.MONTH)  //同一年
//                            :   ((end.get(Calendar.YEAR) - start.get(Calendar.YEAR) >= 2) //年数差超过2年
//                            ? (end.get(Calendar.YEAR) - start.get(Calendar.YEAR) - 1)
//                            * 12 + start.getActualMaximum(Calendar.MONTH) - start.get(Calendar.MONTH)
//                            + end.get(Calendar.MONTH) + 1
//                            : start.getActualMaximum(Calendar.MONTH) - start.get(Calendar.MONTH)
//                            + end.get(Calendar.MONTH) + 1);  //年数差为1，Calendar.get(MONTH) 第一月是0，所以+1
//            System.out.println(subMonthCount);


//        String str = HttpUtils.sendPost("http://wechat.xrtn.dmpp.net.cn/children/frontend/web/index.php?r=wechat/sendbookingsuccess","patientName="+patientName+"&bookingTime="+bookingInfo.getBookingTime()+"&SubclinicName="+bookingInfo.getSubclinicName()+"&doctorName="+sysUserInfo.getUserName());
//        System.out.println("str = " + str );
//        }

    }


    /**
     * @author jerry.chen
     * @param brithday
     * @return
     * @throws ParseException
     *             根据生日获取年龄;
     */
    public static int getCurrentAgeByBirthdate(String brithday)
            throws ParseException, Exception {
        try {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat formatDate = new SimpleDateFormat(YYYY_MM_DD);
            String currentTime = formatDate.format(calendar.getTime());
            Date today = formatDate.parse(currentTime);
            Date brithDay = formatDate.parse(brithday);

            return today.getYear() - brithDay.getYear();
        } catch (Exception e) {
            return 0;
        }
    }
    /**
     * @author jerry.chen
     * @return
     * @throws ParseException
     *             根据生日获取年龄;
     */
    public static int daysBetween(Date early, Date late)
            throws ParseException, Exception {
        try {

            java.util.Calendar calst = java.util.Calendar.getInstance();
            java.util.Calendar caled = java.util.Calendar.getInstance();
            calst.setTime(early);
            caled.setTime(late);
            //设置时间为0时
            calst.set(java.util.Calendar.HOUR_OF_DAY, 0);
            calst.set(java.util.Calendar.MINUTE, 0);
            calst.set(java.util.Calendar.SECOND, 0);
            caled.set(java.util.Calendar.HOUR_OF_DAY, 0);
            caled.set(java.util.Calendar.MINUTE, 0);
            caled.set(java.util.Calendar.SECOND, 0);
            //得到两个日期相差的天数
            int days = ((int) (caled.getTime().getTime() / 1000) - (int) (calst
                    .getTime().getTime() / 1000)) / 3600 / 24;
            return days;
        } catch (Exception e) {
            return 0;
        }
    }
    public int getDateSpace(String date2)
            throws ParseException {

        int result = 0;

        Calendar calst = Calendar.getInstance();;
        Calendar caled = Calendar.getInstance();
        Date today = DateUtils.parse(DateUtils.format(new Date()),DateUtils.YYYY_MM_DD);
        calst.setTime(today);
        Date brithDay = DateUtils.parse(date2,DateUtils.YYYY_MM_DD);
        caled.setTime(brithDay);

        //设置时间为0时
        calst.set(Calendar.HOUR_OF_DAY, 0);
        calst.set(Calendar.MINUTE, 0);
        calst.set(Calendar.SECOND, 0);
        caled.set(Calendar.HOUR_OF_DAY, 0);
        caled.set(Calendar.MINUTE, 0);
        caled.set(Calendar.SECOND, 0);
        //得到两个日期相差的天数
        int days = ((int)(caled.getTime().getTime()/1000)-(int)(calst.getTime().getTime()/1000))/3600/24;

        return days;
    }


}
